<template>
  <div class="container">
    <Aside></Aside>
    <div class="main-box">
      <Header></Header>
      <div class="table-box">
        <el-button
          @click="
            IsUpdate = true;
            digTitle = '添加信息';
          "
          >添加信息</el-button
        >
        <el-button
          @click="
            IsUpdate = true;
            digTitle = '批量修改';
          "
          >批量修改</el-button
        >
        <el-button @click="deleteMany">删除选中</el-button>
        <span style="margin-right: 10px"></span>
        <el-select v-model="nowSelect" placeholder="请选择">
          <el-option
            v-for="(item, key) in tableData"
            :key="key"
            :label="item.name"
            :value="key"
          >
          </el-option>
        </el-select>
        <el-table
          ref="multipleTable"
          tooltip-effect="dark"
          style="width: 100%"
          max-height="600"
          :data="showData"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="60" fixed></el-table-column>
          <el-table-column
            v-for="(item, key) in fieldData"
            :key="key"
            :label="item.name"
            min-width="100"
          >
            <template slot-scope="scope">
              <div v-if="item.type == '文本'">{{ scope.row.content[key] }}</div>
              <el-image
                v-if="item.type == '图片'"
                :src="scope.row.content[key]"
								@click="openUpload(scope.row.id,item.id)"
              >
                <div slot="error" class="image-slot">
                  <el-button
                    type="primary"
                    size="mini"
                    @click="openUpload(scope.row.id,item.id)"
                    >上传图片</el-button
                  >
                </div>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column width="300">
            <template slot="header">
              <el-input
                v-model="search"
                size="mini"
                placeholder="输入关键字搜索"
              />
            </template>
            <template slot-scope="scope">
              <el-popover placement="left" width="110" trigger="hover">
                <img :src="scope.row.qrcodeUrl" width="110" height="110" />
                <el-button
                  slot="reference"
                  type="success"
                  size="small"
                  icon="el-icon-share"
                  style="margin-right: 10px"
                  >分享</el-button
                >
              </el-popover>
              <el-button
                type="primary"
                size="small"
                icon="el-icon-edit"
                @click="updateRows(scope.$index)"
                >修改
              </el-button>
              <el-button
                type="danger"
                size="small"
                icon="el-icon-delete"
                @click="deleteRows(scope.$index)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          background
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 15, 50]"
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper, sizes"
          :total="total"
        >
        </el-pagination>
      </div>
      <!--增加/修改弹窗-->
      <el-dialog :title="digTitle" :visible.sync="IsUpdate">
        <el-form label-width="100px">
          <el-form-item
            v-for="(item, index) in fieldData"
            :label="item.name"
            :key="index"
          >
            <el-input v-model="addData[index]"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              @click="addSure"
              v-show="digTitle == '添加信息'"
              type="primary"
              >保存添加</el-button
            >
            <el-button
              @click="updateSure"
              v-show="digTitle == '修改信息'"
              type="primary"
              >保存修改</el-button
            >
            <el-button
              @click="updateMany"
              v-show="digTitle == '批量修改'"
              type="primary"
              >全部修改</el-button
            >
            <el-button @click="IsUpdate = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <el-dialog title="上传图片" :visible.sync="UploadFile.show">
        <input type="file" accept="image/*" ref="uploadFile" style="margin:30px 0"/>
				<br>
				<el-button type="primary" size="mini" @click="UploadPic">确认上传</el-button>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import Aside from "../components/aside.vue";
import Header from "../components/header.vue";
import QRCode from "qrcode";
import qs from "qs";

export default {
  name: "Product",
  data() {
    return {
      nowSelect: 0, //控制显示哪张表
      multipleSelection: [], //
      search: "", //查询关键词
      tableData: [], //所有表
      fieldData: [], //表头
      total: 0, //数据总数
      pageSize: 10,
      currentPage: 1,
      showData: [], //显示数据
      IsUpdate: false, //添加框显示
      addData: [], //添加值数组
      digTitle: "添加信息", //弹框标题
      editId: [], //正在编辑的id
      UploadFile: {
				row_id:null,
				field_id:null,
        show: false,
      }, //上传文件弹出框
    };
  },
  components: {
    Aside,
    Header,
  },
  methods: {
    growCode(row) {
      const mmp = qs.stringify({
        table_id: this.tableData[this.nowSelect].id,
        id: row.id,
      });
      QRCode.toDataURL(`${location.origin}/search?${mmp}`)
        .then((url) => {
          row.qrcodeUrl = url;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    openUpload(row_id,field_id) {
				this.UploadFile.row_id = row_id;
				this.UploadFile.field_id = field_id;
				this.UploadFile.show = true;
		},
		UploadPic(){
			const file = this.$refs.uploadFile.files[0];
			const fd = new FormData();
			fd.append('file', file, file.name);
      fd.append('row_id',this.UploadFile.row_id);
      fd.append('field_id',this.UploadFile.field_id);
			this.$api.upload(fd).then(res=>{
					this.$message.success('上传完成');
					this.UploadFile.show = false;
					this.getData(
              this.tableData[this.nowSelect].id,
              this.currentPage,
              this.pageSize
            );
			})
		},
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    addSure() {
      var that = this;
      this.$api
        .addRows(this.tableData[this.nowSelect].id, this.addData)
        .then((res) => {
          if (res.code === 0) {
            that.$message.success(res.message);
            that.IsUpdate = false;
            that.getData(
              that.tableData[that.nowSelect].id,
              that.currentPage,
              that.pageSize
            );
          } else {
            this.$message.error(res.message);
          }
        });
    },
    deleteRows(index) {
      //删除
      this.$confirm("此操作将永久删除该记录, 是否继续?", "删除确认", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning",
      })
        .then(() => {
          this.$api.deleteRows([this.showData[index].id]).then((res) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getData(
              this.tableData[this.nowSelect].id,
              this.currentPage,
              this.pageSize
            );
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    deleteMany() {
      //批量删除
      let arr = [];
      for (let i = 0; i < this.multipleSelection.length; i++) {
        arr.push(this.multipleSelection[i].id);
      }
      this.$confirm("此操作将永久删除选中的所有记录, 是否继续?", "删除确认", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning",
      })
        .then(() => {
          this.$api.deleteRows(arr).then((res) => {
            this.$message({
              type: "success",
              message: "批量删除成功!",
            });
            this.getData(
              this.tableData[this.nowSelect].id,
              this.currentPage,
              this.pageSize
            );
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    updateRows(index) {
      //修改
      this.IsUpdate = true;
      this.digTitle = "修改信息";
      this.addData = this.showData[index].content;
      this.editId = this.showData[index].id;
    },
    updateSure() {
      this.$api.updateRows(this.editId, this.addData).then((res) => {
        this.$message(res.message);
        if (res.code === 0) {
          this.getData(
            this.tableData[this.nowSelect].id,
            this.currentPage,
            this.pageSize
          );
          this.IsUpdate = false;
        }
      });
    },
    //批量修改
    updateMany() {},
    getData(table_id, page, pageSize) {
      var that = this;
      that.$api.getRows(table_id, null, page, pageSize).then((res) => {
        if (res.code === 0) {
          that.total = res.result.total;
          that.showData = res.result.data.map((item) => {
            let obj = {
              id: item.id,
              qrcodeUrl: "",
              content: [],
            };
            for (var k in item) {
              if (k.indexOf("$") != -1) {
                obj.content.push(item[k].content);
              }
            }
            that.growCode(obj);
            return obj;
          });
					console.log(this.showData)
          
        }
      });
    },
  },
  mounted() {
    var that = this; //进入时查询一次
    that.$api.getTable().then((res) => {
      that.tableData = res.result.data;
      that.$api.getField(that.tableData[that.nowSelect].id).then((res) => {
        that.fieldData = res.result.map((item) => {
          var obj = {
						id:item.id,
            name: item.name,
            type: item.type,
          };
          return obj;
        });
        if (res.code === 0) {
          that.getData(
            that.tableData[that.nowSelect].id,
            that.currentPage,
            that.pageSize
          );
        }
      });
    });
  },
  watch: {
    multipleSelection(val) {
      //多选
    },
    pageSize(val) {
      //每页显示数量
      this.getData(this.tableData[this.nowSelect].id, this.currentPage, val);
    },
    currentPage(val) {
      this.getData(this.tableData[this.nowSelect].id, val, this.pageSize);
    },
    IsUpdate(val) {
      if (!val) {
        this.addData = [];
      }
    },
    nowSelect(val) {
      var that = this;
      that.$api.getField(that.tableData[val].id).then((res) => {
        that.fieldData = res.result.map((item) => {
          var obj = {
            name: item.name,
            type: item.type,
          };
          return obj;
        });
        if (res.code === 0) {
          that.getData(that.tableData[val].id, that.currentPage, that.pageSize);
        }
      });
    },
  },
};
</script>

<style scoped>
.block {
  margin-top: 15px;
}
</style>
